
package com.jf.cloud.supplier.service.impl;

import com.jf.cloud.api.supplier.constant.SupplierStatus;
import com.jf.cloud.api.supplier.vo.SupplierApiDetailVO;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.supplier.constant.AuditStatus;
import com.jf.cloud.supplier.mapper.SupplierAuditingMapper;
import com.jf.cloud.supplier.mapper.SupplierCompanyMapper;
import com.jf.cloud.supplier.mapper.SupplierDetailMapper;
import com.jf.cloud.supplier.model.SupplierAuditing;
import com.jf.cloud.supplier.service.SupplierApplyService;
import com.jf.cloud.supplier.vo.SupplierAuditingVO;
import com.jf.cloud.supplier.vo.SupplierCompanyVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;

/**
 * @author zz
 * @date 2021/4/29 17:23
 */
@Service
public class SupplierApplyServiceImpl implements SupplierApplyService {

    @Autowired
    private SupplierAuditingMapper supplierAuditingMapper;

    @Autowired
    private SupplierDetailMapper supplierDetailMapper;

    @Autowired
    private SupplierCompanyMapper supplierCompanyMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(Long supplierId) {
        Date now = new Date();
        this.checkApplyInfo(supplierId);
        // 插入一条开店申请审核记录
        SupplierAuditingVO supplierAuditingVO = supplierAuditingMapper.getBySupplierId(supplierId);
        SupplierAuditing supplierAuditing = new SupplierAuditing();
        supplierAuditing.setSupplierId(supplierId);
        supplierAuditing.setUserId(AuthUserContext.get().getUserId());
        supplierAuditing.setStatus(AuditStatus.WAITAUDIT.value());
        supplierAuditing.setUpdateTime(now);
        if (Objects.nonNull(supplierAuditingVO)) {
            supplierAuditing.setSupplierAuditingId(supplierAuditingVO.getSupplierAuditingId());
            supplierAuditingMapper.update(supplierAuditing);
        } else {
            supplierAuditing.setCreateTime(now);
            supplierAuditingMapper.save(supplierAuditing);
        }
        // 更新店铺状态为待审核
        supplierDetailMapper.changeSupplierStatus(supplierId, SupplierStatus.OPEN_AWAIT_AUDIT.value());
    }

    private void checkApplyInfo(Long supplierId) {
        SupplierApiDetailVO supplierDetailVO = supplierDetailMapper.getBySupplierId(supplierId);
        if (Objects.nonNull(supplierDetailVO) && Objects.equals(supplierDetailVO.getSupplierStatus(), SupplierStatus.OPEN_AWAIT_AUDIT.value())) {
            throw new LuckException("供应商入驻申请审核中，请不要重复提交");
        }
        SupplierCompanyVO supplierCompanyVO = supplierCompanyMapper.getSupplierCompanyBySupplierIdAndStatus(supplierId, AuditStatus.WAITAUDIT.value());
        if (Objects.isNull(supplierCompanyVO)) {
            throw new LuckException("供应商工商信息未填写");
        }
    }

}
